package Eclass.Question;

import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.taglib.tiles.ImportAttributeTag;
import org.apache.struts.upload.FormFile;

import Candidate.CandidateForm;
import Eclass.EclassForm;
import Eclass.Score.ScoreForm;
import Forum.ForumThreadForm;
import Master.SchoolForm;

public class QuestionAction extends Action {
	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		QuestionForm qForm = (QuestionForm) form;
		QuestionManager qMan = new QuestionManager();
		QuestionImport qImport = new QuestionImport();
		
		HttpSession session = request.getSession(true);
		boolean result;
		
		// --------------------------------------------------------------
		// Navigation ----------------------------------------------------------
		CandidateForm candidateForm = new CandidateForm();
		SchoolForm schoolForm = new SchoolForm();
		EclassForm eClassForm = new EclassForm();
		ForumThreadForm forumForm = new ForumThreadForm();
		ScoreForm scoreForm = new ScoreForm();
		System.out.println("----------------------------------");
		if ("updateCandidate".equalsIgnoreCase(qForm.getTask())) {
			candidateForm.getcModel().setRegisNo("01-13-12- 029");
			candidateForm.setTask("update");
			return mapping.findForward("candidate");
		} else if ("manageTrainee".equalsIgnoreCase(qForm.getTask())) {
			eClassForm.setTask("manageTrainee");
			return mapping.findForward("eclass");
		} else if ("batch".equalsIgnoreCase(qForm.getTask())) {
			eClassForm.setTask("batch");
			return mapping.findForward("eclass");
		} else if ("listExamPrep".equalsIgnoreCase(qForm.getTask())) {
			eClassForm.setTask("listExamPrep");
			return mapping.findForward("eclass");
		} else if ("manageSchool".equalsIgnoreCase(qForm.getTask())) {
			schoolForm.setTask("manageSchool");
			return mapping.findForward("master");
		} else if ("forumPage".equalsIgnoreCase(qForm.getTask())) {
			forumForm.setTask("forumPage");
			return mapping.findForward("forum");
		} else if ("report".equalsIgnoreCase(qForm.getTask())) {
			scoreForm.setTask("report");
			return mapping.findForward("score");
		}
		// ------------------------------------------------------------------------------------------------------------------------------

		//move to insert page
		if ("addQuestion".equalsIgnoreCase(qForm.getTask())) {
			qForm.setListClass(qMan.selectClass());
			//return mapping.findForward("insertQuestion");
			
			//Rere 23 Des 2013
			QuestionModel qm = new QuestionModel();
			List list = new ArrayList();
			
			for (int i = 0; i < 2; i++) {
				QuestionModel qm2 = new QuestionModel();
				qm2.setOptionOfAnswer("");
				qm2.setAnswer("false");
				list.add(qm2);
			}
			qForm.setCurrentTask("insert");
			qForm.setListEdit(list);
			qForm.setqModel(qm);
			return mapping.findForward("editQuestion");
		}
		
		
		
		if("insertQuestion".equalsIgnoreCase(qForm.getTask())) {
//			String answer = "";
//			String answerStat = "";
//			Integer jumlahOption = qForm.getAnswer().length;
//			for (int i = 0; i < jumlahOption; i++) {
//				if(answer.equals("")){
//					answer += qForm.getAnswer()[i].toString();
//				} else {
//					answer += "@#$" + qForm.getAnswer()[i].toString();
//				}
//				if(answerStat.equals("")) {
//					if(qForm.getAnswerStatus()[i].equalsIgnoreCase("true"))
//						answerStat += qForm.getAnswer()[i].toString().substring(0,1);
//				}
//				else {
//					if(qForm.getAnswerStatus()[i].equalsIgnoreCase("true"))
//						answerStat += "@" + qForm.getAnswer()[i].toString().substring(0,1);
//				}
//			}
//			System.out.println("Question: "+ qForm.getqModel().getQuestion().toString());
//			System.out.println("Option of Answer: "+ answer);
//			System.out.println("AnswerStat: "+ answerStat);
//			System.out.println("CLass ID: "+ qForm.getqModel().getClassId().toString());
//			System.out.println("Exam For: "+ qForm.getqModel().getExamFor());
//			qForm.getqModel().setAnswer(answerStat);
//			qForm.getqModel().setOptionOfAnswer(answer);
			
			String answer = "";
			String answerStat = "";
			Integer jumlahOption = qForm.getOptionOfAnswer().length;
			for (int i = 0; i < jumlahOption; i++) {
				if(answer.equals("")){
					answer += qForm.getOptionOfAnswer()[i].toString();
				} else {
					answer += "@#$" + qForm.getOptionOfAnswer()[i].toString();
				}
				
				if(answerStat.equals("")) {
					if(qForm.getAnswer()[i].equalsIgnoreCase("true"))
						answerStat += qForm.getOptionOfAnswer()[i].toString().substring(0,1);
				}
				else {
					if(qForm.getAnswer()[i].equalsIgnoreCase("true"))
						answerStat += "@" + qForm.getOptionOfAnswer()[i].toString().substring(0,1);
				}
			}
			System.out.println("Question: "+ qForm.getqModel().getQuestion().toString());
			System.out.println("Option of Answer: "+ answer);
			System.out.println("AnswerStat: "+ answerStat);
			System.out.println("CLass ID: "+ qForm.getqModel().getClassId().toString());
			System.out.println("Exam For: "+ qForm.getqModel().getExamFor());
			
			qForm.getqModel().setAnswer(answerStat);
			qForm.getqModel().setOptionOfAnswer(answer);
			
			result = qMan.addQuestion(qForm.getqModel());
			this.setResult(result, "Add new question", session, qForm.getTask());			
//				return mapping.findForward("manageQuestion");
		}
		
		if ("Excel".equalsIgnoreCase(qForm.getTask())) {
			System.out.println("1");
			// Process the FormFile

			FormFile myFile = qForm.getFilePath();
			// Get the file name
			String fileName = qForm.getqModel().getFileName();

			// Get the servers upload directory real path name
			String directoryPath = "tesUploadFile\\ExamQuestions\\";
			String filePath = getServlet().getServletContext().getRealPath("/")
					+ directoryPath;
			System.out.println("2");
			System.out.println("Filename " + fileName);

			/* Save file on the server */
			if (!fileName.equals("")) {
				System.out.println("3");
				System.out.println("Server path: " + filePath);
				// Create file
				File fileToCreate = new File(filePath, fileName);

				// If file does not exists create file
				if (!fileToCreate.exists()) {
					System.out.println("4");
					FileOutputStream fileOutStream = new FileOutputStream(
							fileToCreate);
					fileOutStream.write(myFile.getFileData());
					fileOutStream.flush();
					fileOutStream.close();
					System.out.println("5");
					System.out.println("6");
				}
				System.out.println("7");
			}

			String fullFilePath = filePath + fileName;
			System.out.println(fullFilePath);
			// Set file name to the request object
			request.setAttribute("directoryPath", directoryPath);
			request.setAttribute("fileName", fileName);
			System.out.println("8");
			// filesharingManager.addFile(fileShareForm.getModelFile());
			List sheetData = new ArrayList();
			sheetData = QuestionImport.CekSoal(fullFilePath);

			String append = "";
			String setQuestion = "";
			System.out.println(sheetData.size());

			for (int i = 1; i < sheetData.size(); i++) {
				List list = (List) sheetData.get(i);
				if (list.size() > 1) {
					if (append != "") {
						qForm.getqModel().setOptionOfAnswer(append);
						qMan.addQuestion(qForm.getqModel());
						System.out.println(append);
					}

					append = "";
					for (int j = 0; j < list.size(); j++) {
						if(j != 0){
							Cell cell = (Cell) list.get(j);
							if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
								setQuestion += cell.getNumericCellValue();
								System.out.print(cell.getNumericCellValue());
							} else if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
								setQuestion += cell.getRichStringCellValue();
								System.out.print(cell.getRichStringCellValue());
							} else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
								setQuestion += cell.getBooleanCellValue();
							}
						}
						if (j == 1) {
							String temp[] = setQuestion.split("-");
							qForm.getqModel().setClassId(temp[0].toString());
							setQuestion = "";
						} else if (j == 2) {
							setQuestion = setQuestion.replaceAll("\n", "<br />");
							setQuestion = setQuestion.replaceAll("  ", "&nbsp;");
							qForm.getqModel().setQuestion(setQuestion);
							setQuestion = "";
						} else if (j == 3) {
							setQuestion=setQuestion.replaceAll(",", "@");
							qForm.getqModel().setAnswer(setQuestion);
							setQuestion="";
						}
						if (j < list.size() - 1) {
							System.out.print(", ");
						}

					}
					System.out.println("");
				} else {

					for (int j = 0; j < list.size(); j++) {
						Cell cell = (Cell) list.get(j);
						if(append.equals("")){
						if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
							append += cell.getNumericCellValue();
						} else if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
							append +=  cell.getRichStringCellValue();
						} else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
							append +=  cell.getBooleanCellValue();
						}
						}
						else{
							if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
								append += "@#$" + cell.getNumericCellValue();
							} else if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
								append += "@#$" + cell.getRichStringCellValue();
							} else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
								append += "@#$" + cell.getBooleanCellValue();
							}
						}

					}

				}
				if ((sheetData.size() - 1) == i && append != "") {
					qForm.getqModel().setOptionOfAnswer(append);
					qMan.addQuestion(qForm.getqModel());
					System.out.println(append);
					append = "";
				}

			}

			File excelFile = new File(fullFilePath);
			excelFile.delete();
			System.out.println("HASIl------");

			// return mapping.findForward("success");
			// return mapping.findForward("insertQuestion");

			/*
			 * filesharingManager.addFile(fileShareForm.getModelFile());
			 * fileShareForm.setListFile(filesharingManager.selectAll()); return
			 * mapping.findForward("manageFile");
			 */
		}
		if("updateQuestion".equalsIgnoreCase(qForm.getTask())) {
			String answer = "";
			String answerStat = "";
			Integer jumlahOption = qForm.getOptionOfAnswer().length;
			for (int i = 0; i < jumlahOption; i++) {
				if(answer.equals("")){
					answer += qForm.getOptionOfAnswer()[i].toString();
				} else {
					answer += "@#$" + qForm.getOptionOfAnswer()[i].toString();
				}
				if(answerStat.equals("")) {
					if(qForm.getAnswer()[i].equalsIgnoreCase("true"))
						answerStat += qForm.getOptionOfAnswer()[i].toString().substring(0,1);
				}
				else {
					if(qForm.getAnswer()[i].equalsIgnoreCase("true"))
						answerStat += "@" + qForm.getOptionOfAnswer()[i].toString().substring(0,1);
				}
			}
			System.out.println("Question: "+ qForm.getqModel().getQuestion().toString());
			System.out.println("Option of Answer: "+ answer);
			System.out.println("AnswerStat: "+ answerStat);
			System.out.println("CLass ID: "+ qForm.getqModel().getClassId().toString());
			System.out.println("Exam For: "+ qForm.getqModel().getExamFor());
			
			qForm.getqModel().setAnswer(answerStat);
			qForm.getqModel().setOptionOfAnswer(answer);
			
			result = qMan.updateQuestion(qForm.getqModel());
			this.setResult(result, "Update question", session, qForm.getTask());
//				return mapping.findForward("manageQuestion");
		}
		if("update".equalsIgnoreCase(qForm.getTask())) {
			QuestionModel qm = new QuestionModel();
			qm = qMan.selectUpdate(qForm.getId().toString());
			
			String ques = qm.getPt1().toString();
			String opAns = qm.getApt1().toString();
			if(qm.getPt2() == null) {
			} else {
				ques += qm.getPt2().toString();
			}
			if(qm.getPt3() == null) {
			} else {
				ques += qm.getPt3().toString();
			}
			if(qm.getPt4() == null) {
			} else {
				ques += qm.getPt4().toString();
			}
			if(qm.getPt5() == null) {
			} else {
				ques += qm.getPt5().toString();
			}
			
			if(qm.getApt2() == null) {
			} else {
				opAns += qm.getApt2().toString();
			}
			if(qm.getApt3() == null) {
			} else {
				opAns += qm.getApt3().toString();
			}
			if(qm.getApt4() == null) {
			} else {
				opAns += qm.getApt4().toString();
			}
			if(qm.getApt5() == null) {
			} else {
				opAns += qm.getApt5().toString();
			}
			qm.setQuestion(ques);
//			System.out.println("111111111111111111111111111111111111111111111111: "+opAns);
			qm.setOptionOfAnswer(opAns);
//			System.out.println("3333333333333333333333333333333333333333333333: " + qm.getOptionOfAnswer());
			String[] a = qm.getOptionOfAnswer().toString().split("[@][#][$]");
			String[] b = qm.getAnswer().toString().split("[@]");
//			for (int i = 0; i < b.length; i++) {
//				System.out.println("========================: " + b[i].toString());
//			}
			
			List list = new ArrayList();
			
			for (int i = 0; i < a.length; i++) {
				QuestionModel qm2 = new QuestionModel();
				qm2.setOptionOfAnswer(a[i].toString());
				
				for (int j = 0; j < b.length; j++) {
					if(a[i].toString().substring(0,1).equalsIgnoreCase(b[j].toString())) {
						qm2.setAnswer("true");
						break;
					}
					else {
						qm2.setAnswer("false");
					}
				}
				list.add(qm2);
			}
			qForm.setCurrentTask("update");
			qForm.setListClass(qMan.selectClass());
			qForm.setListEdit(list);
			qForm.setqModel(qm);
			return mapping.findForward("editQuestion");
		}
		
		if("delete".equalsIgnoreCase(qForm.getTask())) {
			System.out.println("id delete: " + qForm.getId());
			result = qMan.deleteQuestion(qForm.getId().toString());
			this.setResult(result, "Delete question", session, qForm.getTask());
//			return mapping.findForward("insertQuestion");
		}
		if("uploadImg".equalsIgnoreCase(qForm.getTask())){
			System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa: " + qForm.getCurrentTask().toString());
			if("update".equalsIgnoreCase(qForm.getCurrentTask())) {
				qForm.setTask("update");
			}
			
			FormFile myFile = qForm.getImgPath();
			String fileName = qForm.getFileName();
			
			String directoryPath = "tesUploadFile\\ImageQuestion\\";
			String filePath = getServlet().getServletContext().getRealPath("/")
			+ directoryPath;
			if (!fileName.equals("")) {

				System.out.println("Server path: " + filePath);
				// Create file
				File fileToCreate = new File(filePath, fileName);

				// If file does not exists create file
				if (!fileToCreate.exists()) {
				FileOutputStream fileOutStream = new FileOutputStream(
				fileToCreate);
				fileOutStream.write(myFile.getFileData());
				fileOutStream.flush();
				fileOutStream.close();
				} else {
					String oldFileName = fileName.substring(0,fileName.lastIndexOf("."));
					String fileType = fileName.substring(fileName.lastIndexOf("."), fileName.length());
					
//					java.text.DateFormat df = new java.text.SimpleDateFormat("EEEE, dd MMMM yyyy");
//					df.format(new java.util.Date());
//					String date = df.toString();
//					System.out.println(date);
					
					java.text.DateFormat df2 = new java.text.SimpleDateFormat("yyyyMMddhhmmss");
					String date = df2.format(new java.util.Date()).toString();
					System.out.println(date);
					
					String newFileName = date.toString() + fileType;
				
				    // File (or directory) with new name
				    File file2 = new File(filePath, newFileName);
				    /*if(file2.exists()) throw new java.io.IOException("file exists");*/

				    // Rename file (or directory)
				    boolean success = fileToCreate.renameTo(file2);
				    if (!success) {
				        // File was not successfully renamed
//				    	session.setAttribute("result", "File was not successfully renamed");
				    	System.out.println("rename gagal");
				    } else {
				    	FileOutputStream fileOutStream = new FileOutputStream(fileToCreate);
						fileOutStream.write(myFile.getFileData());
						fileOutStream.flush();
						fileOutStream.close();
					}
				    fileName = newFileName;
				}
			}
			String fullFilePath = filePath + fileName;
			
			request.setAttribute("directoryPath", directoryPath);
			request.setAttribute("fileName", fileName);
			
			response.setContentType("text/text;charset=utf-8");
			response.setHeader("cache-control", "no-cache");
			PrintWriter out = response.getWriter();
			String append = fullFilePath;
			
			out.println(append);
			QuestionModel qm = new QuestionModel();
			qm = qForm.getqModel();
			
			List list = new ArrayList();

			for (int i = 0; i < qForm.getOptionOfAnswer().length; i++) {
				QuestionModel qm2 = new QuestionModel();
				qm2.setOptionOfAnswer(qForm.getOptionOfAnswer()[i].toString());
				qm2.setAnswer(qForm.getAnswer()[i]);
				list.add(qm2);
			}		
			qForm.setListEdit(list);
			qForm.setListClass(qMan.selectClass());
			qForm.setImgPathCopy(directoryPath + fileName);
			System.out.println(qForm.getImgPathCopy().toString());
			return mapping.findForward("editQuestion");
//			out.flush();
			//return null;
		}
		List a = new ArrayList();
		List b = new ArrayList();
		a = qMan.selectQuestion();
		for (int i = 0; i < a.size(); i++) {
			QuestionModel qm = new QuestionModel();
			qm = (QuestionModel) a.get(i);
			String ques = qm.getPt1().toString();
			String opAns = qm.getApt1().toString();
			if(qm.getPt2() == null) {
			} else {
				ques += qm.getPt2().toString();
			}
			if(qm.getPt3() == null) {
			} else {
				ques += qm.getPt3().toString();
			}
			if(qm.getPt4() == null) {
			} else {
				ques += qm.getPt4().toString();
			}
			if(qm.getPt5() == null) {
			} else {
				ques += qm.getPt5().toString();
			}
			
			if(qm.getApt2() == null) {
			} else {
				opAns += qm.getApt2().toString();
			}
			if(qm.getApt3() == null) {
			} else {
				opAns += qm.getApt3().toString();
			}
			if(qm.getApt4() == null) {
			} else {
				opAns += qm.getApt4().toString();
			}
			if(qm.getApt5() == null) {
			} else {
				opAns += qm.getApt5().toString();
			}
			qm.setOptionOfAnswer(opAns);
//			System.out.println("111111111111111111111111111111111111111111111111: "+opAns);
			String optionAnswer = qm.getOptionOfAnswer().toString().replace("@#$", "<br />");
			String ans = qm.getAnswer().toString().replace("@", ",");
//			System.out.println("========================================: "+optionAnswer +" , " + ans);
			qm.setQuestion(ques);
			qm.setOptionOfAnswer(optionAnswer);
			qm.setAnswer(ans);
			b.add(qm);
		}
		qForm.setListQuestion(b);

		return mapping.findForward("manageQuestion");

	}
	
	public void setResult(boolean result, String action, HttpSession session, String task){
		String resultText = "";
		if(result){
			resultText = action + " data succeed.";
		}else{
			resultText = action + " data failed.";
		}
		session.setAttribute("result", resultText);
	}
}
